{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> [Kaggle入门教程2-改进特征](http://www.cnblogs.com/cutd/p/5713525.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 改进模型\n",
    "## 使用sklearn随机森林拟合非线性成分\n",
    "- 用储存在**alg**的随机森林算法去做交叉验证。用predictions去预测Survived列。将结果赋值到**scores**。\n",
    "- 使用**model_selection.cross_val_score**来完成这些。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "titanic = pd.read_csv('../input/train.csv')\n",
    "# 处理Age中的缺失值\n",
    "titanic['Age'] = titanic['Age'].fillna(titanic['Age'].median())\n",
    "# 量化Sex\n",
    "titanic.loc[titanic['Sex'] == 'male', 'Sex'] = 0\n",
    "titanic.loc[titanic['Sex'] == 'female', 'Sex'] = 1\n",
    "# 量化Embarked\n",
    "titanic['Embarked'] = titanic['Embarked'].fillna('S')\n",
    "titanic.loc[titanic['Embarked'] == 'S', 'Embarked'] = 0\n",
    "titanic.loc[titanic['Embarked'] == 'C', 'Embarked'] = 1\n",
    "titanic.loc[titanic['Embarked'] == 'Q', 'Embarked'] = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.801346801347\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "predictors = [\"Pclass\", \"Sex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", \"Embarked\"]\n",
    "\n",
    "# Initialize our algorithm with the default paramters\n",
    "# n_estimators is the number of trees we want to make\n",
    "# min_samples_split is the minimum number of rows we need to make a split\n",
    "# min_samples_leaf is the minimum number of samples we can have at the place where a tree branch ends (the bottom points of the tree)\n",
    "alg = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2, min_samples_leaf=1)\n",
    "# Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)\n",
    "scores = cross_val_score(alg, titanic[predictors], titanic[\"Survived\"],cv=3)\n",
    "\n",
    "# Take the mean of the scores (because we have one for each fold)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 调参\n",
    "- 增加我们使用的树的数量会很大的提升预测的准确率，训练更多的树会花费更多的时间\n",
    "- 调整**min_samples_split**和**min_samples_leaf**变量来减少过拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.820426487093\n"
     ]
    }
   ],
   "source": [
    "alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=4, min_samples_leaf=2)\n",
    "# Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)\n",
    "scores = cross_val_score(alg, titanic[predictors], titanic[\"Survived\"], cv=3)\n",
    "\n",
    "# Take the mean of the scores (because we have one for each fold)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成新特征\n",
    "- 一些点子：\n",
    "  - 名字的长度——这和那人有多富有，所以在泰坦尼克上的位置有关。\n",
    "  - 一个家庭的总人数(**SibSp**+**Parch**)。\n",
    "- 使用pandas数据框的**.apply**方法来生成特征。这会对你传入数据框(dataframe)或序列(series)的每一个元素应用一个函数。我们也可以传入一个**lambda**函数使我们能够定义一个匿名函数。\n",
    "- 一个匿名的函数的语法是**lambda x:len(x)**。x将传入的值作为输入值——在本例中，就是乘客的名字。表达式的右边和返回结果将会应用于x。**.apply**方法读取这些所有输出并且用他们构造出一个pandas序列。我们可以将这个序列赋值到一个数据框列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Generating a familysize column\n",
    "titanic[\"FamilySize\"] = titanic[\"SibSp\"] + titanic[\"Parch\"]\n",
    "\n",
    "# The .apply method generates a new series\n",
    "titanic[\"NameLength\"] = titanic[\"Name\"].apply(lambda x: len(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用头衔\n",
    "- 从乘客的名字中提取出他们的头衔。头衔的格式是**Master.,Mr.,Mrs.**，以一个大写字母开头，后面是小写字母，最后以.结尾。有一些非常常见的头衔，也有一些“长尾理论”中的一次性头衔只有仅仅一个或者两个乘客使用。第一步使用**正则表达式**提取头衔，然后将每一个唯一头衔匹配成(map)整型数值。\n",
    "- 之后我们将得到一个准确的和Title相对应的数值列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mr          517\n",
      "Miss        182\n",
      "Mrs         125\n",
      "Master       40\n",
      "Dr            7\n",
      "Rev           6\n",
      "Col           2\n",
      "Major         2\n",
      "Mlle          2\n",
      "Countess      1\n",
      "Ms            1\n",
      "Lady          1\n",
      "Jonkheer      1\n",
      "Don           1\n",
      "Mme           1\n",
      "Capt          1\n",
      "Sir           1\n",
      "Name: Name, dtype: int64\n",
      "1     517\n",
      "2     183\n",
      "3     125\n",
      "4      40\n",
      "5       7\n",
      "6       6\n",
      "7       5\n",
      "10      3\n",
      "8       3\n",
      "9       2\n",
      "Name: Name, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "# A function to get the title from a name.\n",
    "def get_title(name):\n",
    "    # Use a regular expression to search for a title.  Titles always consist of capital and lowercase letters, and end with a period.\n",
    "    title_search = re.search(' ([A-Za-z]+)\\.', name)\n",
    "    # If the title exists, extract and return it.\n",
    "    if title_search:\n",
    "        return title_search.group(1)\n",
    "    return \"\"\n",
    "\n",
    "# Get all the titles and print how often each one occurs.\n",
    "titles = titanic[\"Name\"].apply(get_title)\n",
    "print(pd.value_counts(titles))\n",
    "\n",
    "# Map each title to an integer.  Some titles are very rare, and are compressed into the same codes as other titles.\n",
    "title_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Dr\": 5, \"Rev\": 6, \"Major\": 7, \"Col\": 7, \"Mlle\": 8, \"Mme\": 8, \"Don\": 9, \"Lady\": 10, \"Countess\": 10, \"Jonkheer\": 10, \"Sir\": 9, \"Capt\": 7, \"Ms\": 2}\n",
    "for k,v in title_mapping.items():\n",
    "    titles[titles == k] = v\n",
    "\n",
    "# Verify that we converted everything.\n",
    "print(pd.value_counts(titles))\n",
    "\n",
    "# Add in the title column.\n",
    "titanic[\"Title\"] = titles"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 家族\n",
    "- 生成一个特征来表示哪些人是一个家族。因为幸存看起来非常依靠你的家族和你旁边的人，这是一个成为好特征的好机会。\n",
    "- 通过FamilySize连接某些人的姓来得到一个家庭编号。然后我们将基于他们的家庭编号给每个人赋值一个代码。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-1      800\n",
      " 14       8\n",
      " 149      7\n",
      " 63       6\n",
      " 50       6\n",
      " 59       6\n",
      " 17       5\n",
      " 384      4\n",
      " 27       4\n",
      " 25       4\n",
      " 162      4\n",
      " 8        4\n",
      " 84       4\n",
      " 340      4\n",
      " 43       3\n",
      " 269      3\n",
      " 58       3\n",
      " 633      2\n",
      " 167      2\n",
      " 280      2\n",
      " 510      2\n",
      " 90       2\n",
      " 83       1\n",
      " 625      1\n",
      " 376      1\n",
      " 449      1\n",
      " 498      1\n",
      " 588      1\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import operator\n",
    "# A dictionary mapping family name to id\n",
    "family_id_mapping = {}\n",
    "# A function to get the id given a row\n",
    "def get_family_id(row):\n",
    "    # Find the last name by splitting on a comma\n",
    "    last_name = row[\"Name\"].split(\",\")[0]\n",
    "    # Create the family id\n",
    "    family_id = \"{0}{1}\".format(last_name, row[\"FamilySize\"])\n",
    "    # Look up the id in the mapping\n",
    "    if family_id not in family_id_mapping:\n",
    "        if len(family_id_mapping) == 0:\n",
    "            current_id = 1\n",
    "        else:\n",
    "            # Get the maximum id from the mapping and add one to it if we don't have an id\n",
    "            current_id = (max(family_id_mapping.items(), key=operator.itemgetter(1))[1] + 1)\n",
    "        family_id_mapping[family_id] = current_id\n",
    "    return family_id_mapping[family_id]\n",
    "\n",
    "# Get the family ids with the apply method\n",
    "family_ids = titanic.apply(get_family_id, axis=1)\n",
    "\n",
    "# There are a lot of family ids, so we'll compress all of the families under 3 members into one code.\n",
    "family_ids[titanic[\"FamilySize\"] < 3] = -1\n",
    "\n",
    "# Print the count of each unique id.\n",
    "print(pd.value_counts(family_ids))\n",
    "\n",
    "titanic[\"FamilyId\"] = family_ids"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 找出最好的特征\n",
    "- 一种方法就是使用单特征选择器(univariate feature selection),这种方法的本质是一列一列的遍历计算出和我们想要预测的结果(Survived)最密切关联的那一列。\n",
    "- sklearn有一个叫做SelectKBest的函数将会帮助我们完成特征选择。这个函数会从数据中选出最好的特征，并且允许我们指定选择的数量。\n",
    "- 我们已经更新predictors。为titanic数据框做用3折交叉验证预测。用predictors预测Survived列。将结果赋值给scores。\n",
    "- 在做完交叉验证预测之后，将我们的scores的平均值打印出来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEnCAYAAAC5ebgKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAG75JREFUeJzt3XuYZVV95vHva7eIwQu3smUEbVRE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SlfvodS4zt/1GeflDSOcBDbLd9s4eDN9UkoPZAvxzY\nmuZsaEGq4qKompsx9yZXCHggzfTkpXL6HUtQOUp+Ok2Yft32mSNuUtUknU+zkut32LgPfcEMW6wi\n0COWGknvpxkEcErZdQTwQ7d4l6rFNAW+DWXi2u/waO8tu5Faulwilpr9aSZw9W4SvRa4ouWai2YK\nfBsWUnDPJIEesThdQ3NDld66NTuVfa2x/aHyuCQXw9Nobwo+lAR6xCIi6TM0feYPBq6UdGHZfgod\nje5aDFPgW/IPTHNT8JG2aIoEesTi8q5RN4BFMAW+LbavkbTM9r3AyZIuAY4ddbt6EugRi8jUftwy\nqajr/8d32X5fxzUXglHeFHwoGeUSsQhJWg0cB9xFc5TcG6LbxfK5L6G5h+uCnQLfhlHeFHxYCfSI\nRUjS1cC+tm8dQe130EyB/yF9U+DbvJ/pKI3ypuCzlS6XiMXphzST50ZhwU+Bn2efBkZyU/DZSqBH\nLE7HAt+UdAEbd3u8toPaC34K/Dwb2U3BZyuBHrE4fQj4Es1y0V2PNNkauErSgp0CP89GelPw2Ugf\nesQiNMp75S6GKfDzqW+tqP51omABrhWVQI9YhCS9neaG3J9h46Pkzm/OHQtHAj1iEZL0o2l2dzVs\nccFPgV+q0ocesQjZ3nmE5Rf8FPilakHNcoqITZP0xr7nL5zy2tu7akeZTLPM9r22TwYO7Kp2zCyB\nHrG4vLjv+dQ1RLoK1Y2mwEv6C5IlC0L+ESIWF83wfLrttrycJjteTTP6YydgwU62WUrShx6xuGxq\nTHSrIxx6U+Bt99ZgvwtYkmujL1QZ5RKxiAwYE72l7fu3WPti24tiCvxSlSP0iEXE9rIRll80U+CX\nqvShR8SwFs0U+KUqXS4RMZTFNAV+qUqgR0RUIl0uERGVSKBHRFQigR4RUYkEekREJf4DBTY9jsk1\n9eIAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x6cdafd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.811447811448\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.feature_selection import SelectKBest, f_classif\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "predictors = [\"Pclass\", \"Sex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", \"Embarked\", \"FamilySize\", \"Title\", \"FamilyId\"]\n",
    "\n",
    "# Perform feature selection\n",
    "selector = SelectKBest(f_classif, k=5)\n",
    "selector.fit(titanic[predictors], titanic[\"Survived\"])\n",
    "\n",
    "# Get the raw p-values for each feature, and transform from p-values into scores\n",
    "scores = -np.log10(selector.pvalues_)\n",
    "\n",
    "# Plot the scores.  See how \"Pclass\", \"Sex\", \"Title\", and \"Fare\" are the best?\n",
    "plt.bar(range(len(predictors)), scores)\n",
    "plt.xticks(range(len(predictors)), predictors, rotation='vertical')\n",
    "plt.show()\n",
    "\n",
    "# Pick only the four best features.\n",
    "predictors = [\"Pclass\", \"Sex\", \"Fare\", \"Title\"]\n",
    "\n",
    "alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=8, min_samples_leaf=4)\n",
    "# Compute the accuracy score for all the cross validation folds.  (much simpler than what we did before!)\n",
    "scores = cross_val_score(alg, titanic[predictors], titanic[\"Survived\"], cv=3)\n",
    "\n",
    "# Take the mean of the scores (because we have one for each fold)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 梯度提升(Gradient Boosting)\n",
    "- 另外一种方法是以决策树为基础的梯度提升分类器。提升包含了一个接一个的训练决策树，并且将一个树的误差传入到下一棵树。所以每一颗树都是以它之前的所有树为基础构造的。不过如果我们建造太多的树会导致过拟合。当你得到了100棵左右的树，这会非常容易过拟合和训练出数据集中的怪特征。当我们的数据集极小时，我们将会把树的数量限制在25。\n",
    "- 另外一种防止过拟合的方法就是限制在梯度提升过程中建立的每一棵树的深度。我们将树的高度限制到3来分避免过拟合。\n",
    "- 我们将试图用提升来替换掉我们的随机森林方法并且观察是否会提升我们的预测准确率。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 集成(Ensembling)\n",
    "- 为了提升我们的预测准确率，我们能做的一件事就是集成不同的分类器。集成的意思就是我们利用一系列的分类器的信息来生成预测结果而不是仅仅用一个。在实践中，这意味着我们是求他们预测结果的平均值。\n",
    "- 通常来说，我们集成越多的越不同的模型，我们结果的准确率就会越高。多样性的意思是模型从不同列生成结果，或者使用一个非常不同的方法来生成预测结果。集成一个随机森林和一个决策树大概不会得到一个非常好的结果，因为他们非常的相似。换句话说，集成一个线性回归和一个随机森林可以工作得非常棒。\n",
    "- 一个关于集成的警示就是我们使用的分类器的准确率必须都是差不多的。集成一个分类器的准确率比另外一个差得多将会导致最后的结果也变差。\n",
    "- 在这一节中，我们将会集成基于大多数线性预测训练的逻辑回归(有一个线性排序，和Survived有一些关联)和一个在所有预测元素上训练的梯度提升树。\n",
    "- 在我们集成的时候会保持事情的简单——我们将会求我们从分类器中得到的行概率(0~1)的平均值，然后假定所有大于0.5的匹配成1，小于等于0.5的匹配成0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.278338945006\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import GradientBoostingClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.model_selection import KFold\n",
    "import numpy as np\n",
    "\n",
    "# The algorithms we want to ensemble.\n",
    "# We're using the more linear predictors for the logistic regression, and everything with the gradient boosting classifier.\n",
    "algorithms = [\n",
    "    [GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3), [\"Pclass\", \"Sex\", \"Age\", \"Fare\", \"Embarked\", \"FamilySize\", \"Title\", \"FamilyId\"]],\n",
    "    [LogisticRegression(random_state=1), [\"Pclass\", \"Sex\", \"Fare\", \"FamilySize\", \"Title\", \"Age\", \"Embarked\"]]\n",
    "]\n",
    "\n",
    "# Initialize the cross validation folds\n",
    "folder = KFold(n_splits=3, random_state=1)\n",
    "\n",
    "predictions = []\n",
    "for train, test in folder.split(titanic['Age']):\n",
    "    train_target = titanic[\"Survived\"].iloc[train]\n",
    "    full_test_predictions = []\n",
    "    # Make predictions for each algorithm on each fold\n",
    "    for alg, predictors in algorithms:\n",
    "        # Fit the algorithm on the training data.\n",
    "        alg.fit(titanic[predictors].iloc[train,:], train_target)\n",
    "        # Select and predict on the test fold.  \n",
    "        # The .astype(float) is necessary to convert the dataframe to all floats and avoid an sklearn error.\n",
    "        test_predictions = alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]\n",
    "        full_test_predictions.append(test_predictions)\n",
    "    # Use a simple ensembling scheme -- just average the predictions to get the final classification.\n",
    "    test_predictions = (full_test_predictions[0] + full_test_predictions[1]) / 2\n",
    "    # Any value over .5 is assumed to be a 1 prediction, and below .5 is a 0 prediction.\n",
    "    test_predictions[test_predictions <= .5] = 0\n",
    "    test_predictions[test_predictions > .5] = 1\n",
    "    predictions.append(test_predictions)\n",
    "\n",
    "# Put all the predictions together into one array.\n",
    "predictions = np.concatenate(predictions, axis=0)\n",
    "\n",
    "# Compute accuracy by comparing to the training data.\n",
    "accuracy = sum(predictions[predictions == titanic[\"Survived\"]]) / len(predictions)\n",
    "print(accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 在测试集上匹配我们的变化\n",
    "- 生成NameLength,表示名字的长度。\n",
    "- 生成FamilySize,表示家庭的大小。\n",
    "- 添加Title列，保持和我们之前做的匹配一样。\n",
    "- 添加FamilyId列，测试数据集合训练数据集的id保持一致。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1     240\n",
      "2      79\n",
      "3      72\n",
      "4      21\n",
      "7       2\n",
      "6       2\n",
      "10      1\n",
      "5       1\n",
      "Name: Title, dtype: int64\n",
      "{\"O'Sullivan0\": 426, 'Mangan0': 620, 'Lindqvist1': 543, 'Denkoff0': 297, 'Rouse0': 413, 'Berglund0': 207, 'Meo0': 142, 'Arnold-Franchi1': 49, 'Chronopoulos1': 71, 'Skoog5': 63, 'Widener2': 329, 'Pengelly0': 217, 'Goncalves0': 400, 'Myhrman0': 626, 'Beane1': 456, 'Moss0': 104, 'Carlsson0': 610, 'Nicholls2': 136, 'Jussila1': 110, 'Jussila0': 483, 'Long0': 632, 'Wheadon0': 33, 'Connolly0': 261, 'Hansen2': 680, 'Stephenson1': 493, 'Davies0': 336, 'Silven2': 359, 'Vanden Steen0': 311, 'Astor1': 571, 'Patchett0': 480, 'Johanson0': 184, 'Coleridge0': 220, 'Christmann0': 87, 'Carter3': 340, 'Compton2': 665, 'Carter1': 226, 'Turkula0': 414, 'Hassab0': 558, 'Saad0': 566, 'Mellors0': 208, 'Mamee0': 36, 'Madsen0': 119, 'Anderson0': 395, 'Kraeff0': 42, 'Robbins0': 468, 'Lundahl0': 522, 'Gilinski0': 490, 'Porter0': 107, 'Sdycoff0': 352, 'Green0': 204, 'Bishop1': 263, 'Sinkkonen0': 603, 'Otter0': 640, 'Dahl0': 299, 'Troutt0': 582, 'Samaan2': 48, 'Edvardsson0': 553, 'Petroff0': 98, 'Burke0': 134, 'Cardeza1': 556, 'Hawksford0': 599, 'Somerton0': 416, 'Healy0': 248, 'Andersson0': 137, 'Fortune5': 27, 'Andersson6': 14, 'Johnson2': 9, 'Johnson0': 273, 'Coxon0': 91, 'Banfield0': 696, 'McCarthy0': 7, 'Panula5': 50, 'West3': 58, 'Kallio0': 374, 'Hoyt1': 206, 'Hoyt0': 638, 'Mannion0': 589, 'Touma2': 232, 'Futrelle1': 4, 'Jardin0': 507, 'Lemore0': 437, 'Davies2': 460, 'Robert1': 630, 'Butt0': 451, 'Wick2': 286, 'Emanuel0': 628, 'Ibrahim Shawah0': 643, 'Carbines0': 175, 'McEvoy0': 583, 'Moutal0': 75, 'Ling0': 157, 'Watson0': 552, 'Lahoud0': 443, 'Sedgwick0': 302, 'Beesley0': 22, 'Sheerlinck0': 79, 'Hunt0': 218, 'Clifford0': 408, 'Stranden0': 602, 'Ahlin1': 40, 'Woolner0': 55, 'Caram1': 482, 'Sandstrom2': 11, 'Nakid2': 333, 'Frost0': 412, 'Moen0': 73, 'Henry0': 239, 'Persson1': 241, 'Mudd0': 671, 'Glynn0': 32, 'Bowerman1': 312, 'Daniel0': 505, 'Nysten0': 132, 'Saalfeld0': 270, 'Turcin0': 173, 'Nasser1': 10, 'Waelens0': 78, 'Homer0': 502, 'Graham1': 242, 'Graham0': 699, 'Brown0': 177, 'Dorking0': 256, 'Bing0': 72, 'Blank0': 191, 'Tornquist0': 245, 'Olsen1': 180, 'Olsen0': 144, 'Davison1': 304, 'Butler0': 544, 'Calderhead0': 575, 'Cor0': 530, 'Kalvik0': 534, 'Hagland1': 386, 'Boulos2': 131, 'Boulos0': 497, 'Leitch0': 496, 'Endres0': 581, 'Fleming0': 275, 'Natsch1': 247, 'Garfirth0': 614, 'Blackwell0': 300, 'Thayer2': 461, 'Holm0': 657, 'Rekic0': 105, 'Allen0': 5, 'Hendekovic0': 282, 'Svensson0': 424, 'Montvila0': 698, 'Perreault0': 441, 'Francatelli0': 278, 'Gronnestad0': 621, 'Maisner0': 399, 'Radeff0': 537, 'Daly0': 432, 'Jarvis0': 488, 'Bowen0': 515, 'Risien0': 453, 'Walker0': 436, 'Klaber0': 578, 'Wright0': 466, 'Artagaveytia0': 419, 'Navratil2': 138, 'Hays2': 658, 'Seward0': 383, 'Hays0': 279, 'Appleton2': 478, 'Fry0': 654, 'Romaine0': 171, 'de Messemaeker1': 469, 'Gustafsson0': 331, 'Gustafsson2': 101, 'Lulic0': 659, 'Beckwith2': 225, 'Sutton0': 516, 'Cunningham0': 355, 'Behr0': 700, 'Rothschild1': 434, 'Stankovic0': 257, 'Abelson1': 277, 'Lobb1': 230, 'Shellard0': 423, 'Knight0': 593, 'Silverthorne0': 572, \"O'Leary0\": 535, 'Saundercock0': 13, 'Baxter1': 114, 'Elias0': 624, 'Nankoff0': 598, 'Mitkoff0': 533, 'Lines1': 677, 'Burns0': 298, \"O'Driscoll0\": 47, 'Cumings1': 2, 'Culumovic0': 674, 'Penasco y Castellana1': 276, 'Parkes0': 251, 'Duff Gordon1': 467, 'Sloper0': 24, 'Strom2': 228, 'Ringhini0': 327, 'Barah0': 616, 'Richards2': 350, 'Crease0': 67, 'Cavendish1': 600, 'Bjornstrom-Steffansson0': 371, 'Masselmani0': 20, 'Moubarek2': 65, 'Turja0': 555, 'Goldsmith2': 154, 'Fahlstrom0': 210, 'Holverson1': 35, 'Herman3': 510, 'Nenkoff0': 205, 'Nysveen0': 292, 'Eklund0': 617, 'Paulner0': 487, 'Nilsson0': 284, 'Dick1': 563, 'Dantcheff0': 639, 'Swift0': 682, 'Humblen0': 570, 'McCormack0': 661, 'Duane0': 253, 'Ekstrom0': 121, 'Wiseman0': 366, 'Smith0': 160, 'Marvin1': 604, 'Cleaver0': 576, 'Gill0': 683, 'Cameron0': 193, 'Augustsson0': 663, 'Petranec0': 97, 'Stahelin-Maeglin0': 523, 'McDermott0': 80, 'Dean3': 90, 'Laleff0': 691, 'Meyer0': 649, 'Meyer1': 34, 'Johansson0': 100, 'Cacic0': 405, 'Ryerson4': 280, 'Becker3': 167, 'Tobin0': 627, 'Murphy1': 219, 'Goldschmidt0': 93, 'Kink2': 68, 'Weisz1': 125, 'Hold1': 215, 'Stanley0': 420, 'Minahan2': 222, 'Toufik0': 450, 'Minahan1': 354, 'Olsvigen0': 559, 'Odahl0': 307, 'Coleff0': 435, 'Vestrom0': 15, 'Hood0': 70, 'Yousseff0': 421, 'Barton0': 109, 'Icard0': 61, 'Smiljanic0': 148, 'Harmer0': 634, 'Ford4': 84, 'Maioni0': 428, 'Abbing0': 675, 'Oreskovic0': 347, 'Sundman0': 356, 'Kink-Heilmann2': 168, 'Lehmann0': 339, 'Dennis0': 288, 'del Carlo1': 316, 'Najib0': 690, 'Ohman0': 465, 'McCoy2': 272, 'Osen0': 129, 'Pernot0': 166, 'Kent0': 415, 'Turpin1': 41, 'Zabour1': 108, 'Alexander0': 650, 'Palsson4': 8, 'Hogeboom1': 618, 'Keefe0': 404, 'Eustis1': 422, 'Marechal0': 669, 'Uruchurtu0': 30, 'Downton0': 485, 'Ilmakangas1': 591, 'Corn0': 147, 'Parrish1': 236, 'Jerwan0': 406, 'Aks1': 678, 'Lam0': 565, 'Slayter0': 290, 'Weir0': 567, 'Frolicher2': 454, 'Danbom2': 365, 'Alhomaki0': 670, 'Brown2': 548, 'Faunthorpe1': 53, 'Givard0': 195, 'Leyson0': 213, 'Potter1': 692, 'Emir0': 26, 'Slocovski0': 85, 'Celotti0': 86, 'Rood0': 169, 'Betros0': 330, 'Larsson0': 211, 'Andreasson0': 88, 'Vande Walle0': 183, 'Morley0': 396, 'Trout0': 344, 'Thorneycroft1': 372, 'Shorney0': 92, 'Attalah0': 111, 'Ward0': 235, 'Yousif0': 310, 'Wiklund1': 325, 'Thorne0': 233, 'Warren1': 320, 'Milling0': 398, 'Rommetvedt0': 545, 'Pickard0': 370, 'Hassan0': 592, 'Heininen0': 655, 'Bazzani0': 200, 'Plotcharsky0': 335, 'Lindell1': 503, 'Caldwell2': 76, 'Meanwell0': 474, 'Bystrom0': 684, 'Harrison0': 238, 'Goldenberg1': 388, 'Webber0': 117, 'Shelley1': 693, 'Mayne0': 577, 'Honkanen0': 198, 'Karlsson0': 410, 'Calic0': 153, 'Eitemiller0': 538, 'Chapman0': 568, 'Asplund6': 25, 'Peuchen0': 385, 'Cairns0': 244, 'Bailey0': 611, 'Hanna0': 268, 'Garside0': 481, 'Mernagh0': 179, 'Staneff0': 74, 'Toomey0': 393, 'Canavan0': 425, 'Dakic0': 560, 'Foo0': 529, 'Pasic0': 666, 'Novel0': 57, 'Lemberopolous0': 673, 'Hocking4': 625, 'Moran1': 106, 'Abbott2': 252, 'Kvillner0': 377, 'Elias2': 309, 'Doharr0': 476, 'Norman0': 472, 'Leader0': 641, 'Smart0': 402, 'White1': 99, 'Gale1': 348, 'Doling1': 95, 'Moor1': 607, 'Taussig2': 237, 'Pinsky0': 174, 'Gallagher0': 573, 'Markun0': 694, 'de Mulder0': 258, 'Kassem0': 444, 'Yrois0': 182, 'Kantor1': 96, 'Sobey0': 126, 'Shutes0': 506, 'Brocklebank0': 509, 'Cherry0': 234, 'Dooley0': 701, 'Hedman0': 646, 'Madigan0': 181, 'Parr0': 524, 'Campbell0': 401, 'Mullens0': 569, 'Charters0': 363, 'Jonsson0': 477, 'Ostby1': 54, 'Wilhelms0': 551, 'Williams1': 145, 'Williams0': 18, 'Maenpaa0': 221, 'Stone0': 662, 'Lennon1': 46, 'Olsson0': 254, 'Harknett0': 214, 'Horgan0': 508, 'Hart0': 353, 'Hart2': 283, 'Ilett0': 82, 'Baumann0': 156, 'Youseff0': 185, 'Reeves0': 240, 'Thomas1': 645, 'Jensen0': 527, 'Jensen1': 584, 'Cribb1': 150, 'Ross0': 486, 'Andersen-Jensen1': 176, 'Gilnagh0': 146, 'Moran0': 6, 'Coelho0': 123, 'Razi0': 679, 'Reuchlin0': 660, 'Kiernan1': 196, 'Partner0': 295, 'Jermyn0': 322, 'Salkjelsvik0': 103, 'Lahtinen2': 281, 'Drew2': 358, 'Hosono0': 260, 'Danoff0': 289, 'van Billiard2': 143, 'Bracken0': 203, 'Coutts2': 305, 'Connors0': 113, 'Jenkin0': 69, 'Hodges0': 586, 'Vovk0': 442, 'Backstrom1': 188, 'Devaney0': 44, 'Backstrom3': 83, 'Barbara1': 317, \"O'Connell0\": 520, 'Vande Velde0': 608, 'Reynaldo0': 380, 'Isham0': 163, \"O'Brien0\": 463, \"O'Brien1\": 170, 'Giglio0': 130, 'Ponesell0': 644, 'Nicola-Yarred1': 39, 'Angle1': 439, 'Mellinger1': 246, 'Newell1': 197, 'Lang0': 431, 'Davidson1': 549, 'Richard0': 127, 'Ball0': 293, 'Drazenoic0': 122, 'Robins1': 124, 'Richards5': 376, 'Nosworthy0': 51, 'Moore0': 116, 'Newsom2': 128, 'Sjoblom0': 635, 'Zimmerman0': 364, 'Kenyon1': 392, 'Fynney0': 21, 'Laroche3': 43, 'Renouf1': 409, 'Silvey1': 375, 'Christy2': 484, 'Renouf3': 588, 'Theobald0': 612, 'Pekoniemi0': 112, 'Bateman0': 140, 'Spencer1': 31, 'Allison3': 269, 'Cohen0': 186, 'Dimic0': 306, 'Bourke2': 172, 'Farthing0': 447, 'Hamalainen2': 224, 'Karaic0': 504, 'Pettersson0': 648, 'Landergren0': 328, 'Willey0': 532, 'Braund1': 1, 'Slemen0': 652, 'Jalsevac0': 390, 'Harder1': 324, 'Elsbury0': 494, 'Carrau0': 81, 'Sutehall0': 697, 'Sawyer0': 554, 'Vander Planke1': 19, 'Peters0': 557, 'Vander Planke2': 38, 'Dahlberg0': 695, 'Sharp0': 462, 'Sirota0': 667, 'Barkworth0': 521, 'Mack0': 623, 'Sjostedt0': 212, 'Slabenoff0': 499, 'Dodge2': 382, 'Mineff0': 266, 'Hocking3': 449, 'Hickman2': 115, 'Perkin0': 194, 'Stewart0': 64, 'Giles1': 681, 'Lindblom0': 250, 'Meek0': 357, 'Morrow0': 470, 'Newell2': 539, 'Beavan0': 326, 'Balkic0': 688, 'van Melkebeke0': 687, 'Foreman0': 387, 'Hampe0': 378, 'Birkeland0': 351, 'Mockler0': 315, 'Millet0': 391, 'Peter2': 120, 'Yasbeck1': 512, 'Osman0': 642, 'Buss0': 337, 'Sunderland0': 202, 'Lefebre4': 162, 'Bryhl1': 590, 'McGovern0': 314, 'Nye0': 66, 'Davis0': 525, 'Aubart0': 323, 'Spedden2': 287, 'Harris0': 201, 'Harris1': 62, 'McGough0': 433, 'Hewlett0': 16, 'Cann0': 37, 'Mallet2': 656, 'Kirkland0': 517, 'Ridsdale0': 446, 'Connaghton0': 605, 'Stoytcheff0': 475, 'Hippach1': 294, 'Dowdell0': 77, 'Klasen2': 161, 'Rothes0': 613, \"O'Connor0\": 394, 'Ivanoff0': 597, 'Clarke1': 367, 'Scanlan0': 403, 'Troupiansky0': 595, 'Reed0': 227, 'Rintamaki0': 492, 'Chambers1': 587, 'Haas0': 265, 'Greenfield1': 94, 'Jansson0': 341, 'Gheorgheff0': 362, 'Mitchell0': 550, 'Bonnell0': 12, 'Murdlin0': 491, 'Lester0': 651, 'Van Impe2': 361, 'Simonius-Blumer0': 531, 'Torber0': 501, 'Gillespie0': 585, 'Naidenoff0': 259, 'McNamee1': 601, 'de Pelsmaeker0': 255, 'Quick2': 429, 'Byles0': 139, 'Sage10': 149, 'Frolicher-Stehli2': 489, 'Peduzzi0': 389, 'Chibnall1': 155, 'Hakkarainen1': 133, 'Watt0': 151, 'Sirayanian0': 60, 'Leonard0': 165, 'Bissette0': 243, 'Adahl0': 319, 'LeRoy0': 452, 'Tomlin0': 653, 'Kimball1': 513, 'Gavey0': 511, 'Mionoff0': 102, 'Farrell0': 445, 'Goodwin7': 59, 'Strom1': 187, 'Ali0': 192, 'Funk0': 313, 'Van der hoef0': 158, 'Roebling0': 686, 'Simmons0': 473, 'Asim0': 318, 'Rosblom2': 231, 'Lovell0': 209, 'Phillips0': 368, 'Leinonen0': 526, 'Markoff0': 676, 'Levy0': 264, 'Frauenthal2': 540, 'Frauenthal1': 296, 'Baclini3': 384, 'Johannesen-Bratthammer0': 381, 'Jonkoff0': 609, 'Williams-Lambert0': 308, 'Serepeca0': 672, 'Longley0': 518, \"O'Dwyer0\": 28, 'Kelly0': 271, 'Douglas1': 457, 'Crosby2': 455, 'Niskanen0': 345, 'Collander0': 301, 'Gee0': 397, 'Tikkanen0': 334, 'McKane0': 342, 'Molson0': 418, 'Bostandyeff0': 519, 'Ayoub0': 631, 'Rogers0': 45, 'Chip0': 668, 'Cook0': 546, 'Stead0': 229, 'Soholt0': 580, 'Moraweck0': 285, 'Bidois0': 332, 'Taylor1': 547, 'Bradley0': 430, 'Fischer0': 561, 'Barber0': 262, 'Albimona0': 189, 'Hale0': 164, 'Flynn0': 369, 'Sadlier0': 338, 'Keane0': 274, 'Young0': 291, 'Lindahl0': 223, 'Rugg0': 56, 'Johnston3': 633, 'Petterson1': 379, 'Pavlovic0': 440, 'Sivic0': 471, 'Hirvonen1': 411, 'Allum0': 664, 'Harrington0': 500, 'Windelov0': 417, 'Lesurer0': 596, 'Pain0': 343, 'Lievens0': 622, 'Fox0': 303, 'Lewy0': 267, 'McMahon0': 118, 'Greenberg0': 579, 'Heikkinen0': 3, 'Louch1': 373, 'Chapman1': 495, 'Berriman0': 594, 'Moussa0': 321, 'Ryan0': 438, 'Madill1': 562, 'Duran y More1': 685, 'Bengtsson0': 152, 'Harper1': 52, 'Kilgannon0': 629, 'Badt0': 541, 'Salonen0': 448, 'Guggenheim0': 636, 'Widegren0': 349, 'Brewe0': 619, 'Sivola0': 159, 'Nirva0': 615, 'Rice5': 17, 'Andrews0': 647, 'Andrews1': 249, 'Collyer2': 216, 'Strandberg0': 407, 'Colley0': 542, 'Nicholson0': 458, 'Chaffee1': 89, 'Gaskell0': 637, 'Wells2': 606, 'Leeni0': 464, 'Todoroff0': 29, 'Adams0': 346, 'Pears1': 141, 'Sagesser0': 528, 'Carr0': 190, 'McGowan0': 23, 'Hansen0': 514, 'Hansen1': 574, 'Karun1': 564, 'Rush0': 479, 'Matthews0': 360, 'Laitinen0': 427, 'Padro y Manent0': 459, 'Andrew0': 135, 'Vander Cruyssen0': 689, 'Jacobsohn1': 199, 'Lurette0': 178, 'Jacobsohn3': 498, 'Hegarty0': 536}\n"
     ]
    }
   ],
   "source": [
    "titanic_test = pd.read_csv('../input/test.csv')\n",
    "\n",
    "# 处理测试集\n",
    "titanic_test = pd.read_csv(\"../input/test.csv\")\n",
    "titanic_test['Age'] = titanic_test['Age'].fillna(titanic_test['Age'].median())\n",
    "titanic_test['Fare'] = titanic_test['Fare'].fillna(titanic_test['Fare'].median())\n",
    "titanic_test.loc[titanic_test['Sex'] == 'male', 'Sex'] = 0\n",
    "titanic_test.loc[titanic_test['Sex'] == 'female', 'Sex'] = 1\n",
    "titanic_test['Embarked'] = titanic_test['Embarked'].fillna('S')\n",
    "titanic_test.loc[titanic_test['Embarked'] == 'S', 'Embarked'] = 0\n",
    "titanic_test.loc[titanic_test['Embarked'] == 'C', 'Embarked'] = 1\n",
    "titanic_test.loc[titanic_test['Embarked'] == 'Q', 'Embarked'] = 2\n",
    "\n",
    "# First, we'll add titles to the test set.\n",
    "titles = titanic_test[\"Name\"].apply(get_title)\n",
    "# We're adding the Dona title to the mapping, because it's in the test set, but not the training set\n",
    "title_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Dr\": 5, \"Rev\": 6, \"Major\": 7, \"Col\": 7, \"Mlle\": 8, \"Mme\": 8, \"Don\": 9, \"Lady\": 10, \"Countess\": 10, \"Jonkheer\": 10, \"Sir\": 9, \"Capt\": 7, \"Ms\": 2, \"Dona\": 10}\n",
    "for k,v in title_mapping.items():\n",
    "    titles[titles == k] = v\n",
    "titanic_test[\"Title\"] = titles\n",
    "# Check the counts of each unique title.\n",
    "print(pd.value_counts(titanic_test[\"Title\"]))\n",
    "\n",
    "# Now, we add the family size column.\n",
    "titanic_test[\"FamilySize\"] = titanic_test[\"SibSp\"] + titanic_test[\"Parch\"]\n",
    "\n",
    "# Now we can add family ids.\n",
    "# We'll use the same ids that we did earlier.\n",
    "# print(family_id_mapping)\n",
    "\n",
    "family_ids = titanic_test.apply(get_family_id, axis=1)\n",
    "family_ids[titanic_test[\"FamilySize\"] < 3] = -1\n",
    "titanic_test[\"FamilyId\"] = family_ids\n",
    "titanic_test[\"NameLength\"] = titanic_test[\"Name\"].apply(lambda x: len(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 在测试集上做预测\n",
    "- 通过将预测结果小于等于0.5的转换成0,将大于0.5的转换成1，将所有的结果转换成非0即1。\n",
    "- 然后，用.astype(int)方法将预测结果转换成整型——如果你不这样做，Kaggle将会给你0分。\n",
    "- 最后，生成一个第一列是PassengerId，第二列是Survived(这就是预测结果)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "predictors = [\"Pclass\", \"Sex\", \"Age\", \"Fare\", \"Embarked\", \"FamilySize\", \"Title\", \"FamilyId\"]\n",
    "\n",
    "algorithms = [\n",
    "    [GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3), predictors],\n",
    "    [LogisticRegression(random_state=1), [\"Pclass\", \"Sex\", \"Fare\", \"FamilySize\", \"Title\", \"Age\", \"Embarked\"]]\n",
    "]\n",
    "\n",
    "full_predictions = []\n",
    "for alg, predictors in algorithms:\n",
    "    # Fit the algorithm using the full training data.\n",
    "    alg.fit(titanic[predictors], titanic[\"Survived\"])\n",
    "    # Predict using the test dataset.  We have to convert all the columns to floats to avoid an error.\n",
    "    predictions = alg.predict_proba(titanic_test[predictors].astype(float))[:,1]\n",
    "    full_predictions.append(predictions)\n",
    "\n",
    "# The gradient boosting classifier generates better predictions, so we weight it higher.\n",
    "predictions = (full_predictions[0] * 3 + full_predictions[1]) / 4\n",
    "predictions[predictions <= .5] = 0\n",
    "predictions[predictions > .5] = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "predictions = predictions.astype(int)\n",
    "submission = pd.DataFrame({\n",
    "        \"PassengerId\": titanic_test[\"PassengerId\"],\n",
    "        \"Survived\": predictions\n",
    "    })\n",
    "# submission.to_csv('../input/submission.csv', index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 其他改进\n",
    "## 特征方面\n",
    "- 尝试用和船舱相关的特征。\n",
    "- 观察家庭大小特征是否会有帮助——一个家庭中女性的数量多使全家更可能幸存？\n",
    "- 乘客的国籍能为其幸存提高什么帮助？\n",
    "## 算法方面\n",
    "- 尝试在集成中加入随机森林分类器。\n",
    "- 在这个数据上支持向量机也许会很有效。\n",
    "- 可以试试神经网络。\n",
    "- 提升一个不同的基础匪类器也许会更好。\n",
    "## 集成方法\n",
    "- 多数表决是比概率平均更好的集成方法？"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
